import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Ref } from 'vue'
import { 
  getRecommendedTags, 
  getPopularTags, 
  getAiStatistics,
  recognizeFileTags,
  batchRecognizeTags 
} from '@/api/ai'

interface AiTag {
  name: string
  confidence?: number
  category?: string
  parentTag?: string
}

interface AiTagResult {
  fileId: number
  status: string
  tags?: AiTag[]
  objects?: any[]
  scenes?: AiTag[]
  faces?: any[]
  extractedText?: string
  dominantColors?: any[]
  qualityScore?: number
  safetyScore?: number
  recommendedAlbums?: string[]
  processingTime?: number
  errorMessage?: string
  metadata?: Record<string, any>
}

interface ProcessingTask {
  id: string
  fileId: number
  fileName: string
  type: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress: number
  result?: AiTagResult
  startTime: Date
  endTime?: Date
}

export const useAiStore = defineStore('ai', () => {
  // 状态
  const isProcessing = ref(false)
  const processingTasks: Ref<ProcessingTask[]> = ref([])
  const popularTags: Ref<string[]> = ref([])
  const recommendedTags: Ref<string[]> = ref([])
  const statistics = ref<any>({})
  const recentResults: Ref<AiTagResult[]> = ref([])
  
  // AI处理配置
  const processingConfig = ref({
    autoRecognition: true,
    confidenceThreshold: 0.7,
    maxTags: 10,
    enableFaceRecognition: true,
    enableObjectDetection: true,
    enableSceneRecognition: true,
    enableOCR: false,
    enableColorAnalysis: true,
    enableSafetyCheck: true
  })

  // 计算属性
  const pendingTasks = computed(() => 
    processingTasks.value.filter(task => task.status === 'pending')
  )
  
  const processingTasksCount = computed(() => 
    processingTasks.value.filter(task => task.status === 'processing').length
  )
  
  const completedTasks = computed(() => 
    processingTasks.value.filter(task => task.status === 'completed')
  )
  
  const failedTasks = computed(() => 
    processingTasks.value.filter(task => task.status === 'failed')
  )
  
  const processingProgress = computed(() => {
    const total = processingTasks.value.length
    if (total === 0) return 0
    const completed = completedTasks.value.length + failedTasks.value.length
    return Math.round((completed / total) * 100)
  })

  // 动作
  const loadPopularTags = async (limit = 20) => {
    try {
      const response = await getPopularTags(limit)
      if (response.code === 200) {
        popularTags.value = response.data
      }
    } catch (error) {
      console.error('加载热门标签失败:', error)
    }
  }

  const loadRecommendedTags = async (fileType?: string) => {
    try {
      const response = await getRecommendedTags(fileType)
      if (response.code === 200) {
        recommendedTags.value = response.data
      }
    } catch (error) {
      console.error('加载推荐标签失败:', error)
    }
  }

  const loadStatistics = async () => {
    try {
      const response = await getAiStatistics()
      if (response.code === 200) {
        statistics.value = response.data
      }
    } catch (error) {
      console.error('加载AI统计失败:', error)
    }
  }

  const addProcessingTask = (fileId: number, fileName: string, type: string): string => {
    const taskId = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const task: ProcessingTask = {
      id: taskId,
      fileId,
      fileName,
      type,
      status: 'pending',
      progress: 0,
      startTime: new Date()
    }
    
    processingTasks.value.push(task)
    return taskId
  }

  const updateTaskStatus = (taskId: string, status: ProcessingTask['status'], progress?: number) => {
    const task = processingTasks.value.find(t => t.id === taskId)
    if (task) {
      task.status = status
      if (progress !== undefined) {
        task.progress = progress
      }
      if (status === 'completed' || status === 'failed') {
        task.endTime = new Date()
      }
    }
  }

  const updateTaskResult = (taskId: string, result: AiTagResult) => {
    const task = processingTasks.value.find(t => t.id === taskId)
    if (task) {
      task.result = result
      task.status = result.status === 'success' ? 'completed' : 'failed'
      task.endTime = new Date()
      
      // 添加到最近结果
      if (result.status === 'success') {
        recentResults.value.unshift(result)
        if (recentResults.value.length > 50) {
          recentResults.value = recentResults.value.slice(0, 50)
        }
      }
    }
  }

  const recognizeFile = async (fileId: number, fileName: string) => {
    const taskId = addProcessingTask(fileId, fileName, 'recognition')
    
    try {
      updateTaskStatus(taskId, 'processing', 10)
      
      const response = await recognizeFileTags(fileId)
      
      if (response.code === 200) {
        updateTaskResult(taskId, response.data)
        return response.data
      } else {
        updateTaskStatus(taskId, 'failed')
        throw new Error(response.msg || '识别失败')
      }
    } catch (error) {
      updateTaskStatus(taskId, 'failed')
      throw error
    }
  }

  const batchRecognizeFiles = async (files: Array<{ fileId: number; fileName: string }>) => {
    isProcessing.value = true
    
    try {
      const fileIds = files.map(f => f.fileId)
      const taskIds = files.map(file => 
        addProcessingTask(file.fileId, file.fileName, 'batch-recognition')
      )
      
      // 更新所有任务状态为处理中
      taskIds.forEach(taskId => updateTaskStatus(taskId, 'processing', 20))
      
      const response = await batchRecognizeTags(fileIds)
      
      if (response.code === 200) {
        const results = response.data as AiTagResult[]
        
        // 更新每个任务的结果
        results.forEach((result, index) => {
          if (index < taskIds.length) {
            updateTaskResult(taskIds[index], result)
          }
        })
        
        return results
      } else {
        // 标记所有任务为失败
        taskIds.forEach(taskId => updateTaskStatus(taskId, 'failed'))
        throw new Error(response.msg || '批量识别失败')
      }
    } catch (error) {
      throw error
    } finally {
      isProcessing.value = false
    }
  }

  const clearCompletedTasks = () => {
    processingTasks.value = processingTasks.value.filter(
      task => task.status !== 'completed' && task.status !== 'failed'
    )
  }

  const clearAllTasks = () => {
    processingTasks.value = []
  }

  const getTaskById = (taskId: string) => {
    return processingTasks.value.find(task => task.id === taskId)
  }

  const getTasksByFileId = (fileId: number) => {
    return processingTasks.value.filter(task => task.fileId === fileId)
  }

  const updateProcessingConfig = (config: Partial<typeof processingConfig.value>) => {
    processingConfig.value = { ...processingConfig.value, ...config }
  }

  // 标签相关的辅助方法
  const filterTagsByConfidence = (tags: AiTag[], threshold = 0.7) => {
    return tags.filter(tag => !tag.confidence || tag.confidence >= threshold)
  }

  const groupTagsByCategory = (tags: AiTag[]) => {
    const grouped: Record<string, AiTag[]> = {}
    tags.forEach(tag => {
      const category = tag.category || '通用'
      if (!grouped[category]) {
        grouped[category] = []
      }
      grouped[category].push(tag)
    })
    return grouped
  }

  const getTopTags = (tags: AiTag[], limit = 5) => {
    return tags
      .sort((a, b) => (b.confidence || 0) - (a.confidence || 0))
      .slice(0, limit)
  }

  const mergeSimilarTags = (tags: AiTag[]) => {
    // 简单的标签合并逻辑，实际应用中可能需要更复杂的算法
    const merged: AiTag[] = []
    const seen = new Set<string>()
    
    tags.forEach(tag => {
      const normalizedName = tag.name.toLowerCase().trim()
      if (!seen.has(normalizedName)) {
        seen.add(normalizedName)
        merged.push(tag)
      }
    })
    
    return merged
  }

  return {
    // 状态
    isProcessing,
    processingTasks,
    popularTags,
    recommendedTags,
    statistics,
    recentResults,
    processingConfig,
    
    // 计算属性
    pendingTasks,
    processingTasksCount,
    completedTasks,
    failedTasks,
    processingProgress,
    
    // 动作
    loadPopularTags,
    loadRecommendedTags,
    loadStatistics,
    addProcessingTask,
    updateTaskStatus,
    updateTaskResult,
    recognizeFile,
    batchRecognizeFiles,
    clearCompletedTasks,
    clearAllTasks,
    getTaskById,
    getTasksByFileId,
    updateProcessingConfig,
    
    // 辅助方法
    filterTagsByConfidence,
    groupTagsByCategory,
    getTopTags,
    mergeSimilarTags
  }
})